#include "client.h"
#include "ui_client.h"
#include"iostream"
#include"string"
#include"mytcpclient.h"
#include"QtNetwork"
#include"QMessageBox"

client::client(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::client)
{
    ui->setupUi(this);
    instance=this;
    ipTxt=ui->ipTxt;
    portTxt=ui->portTxt;
    rcvMsgBrower=ui->rcvMsgBrower;
    sendMsgEdit=  ui->sendMsgEdit;


    ipTxt->setText(QString::fromStdString(getMyIp()));
    portTxt->setText("12345");

}

client::~client()
{
    delete ui;
}
std::string client::getMyIp(){
    std::string address="";
    // 获取所有网络接口
    QList<QNetworkInterface> interfaces = QNetworkInterface::allInterfaces();

    // 遍历每个网络接口
    for (const QNetworkInterface &interface : interfaces) {
        // 过滤 WiFi 接口
        if (interface.type() == QNetworkInterface::Wifi) {
            // 获取该接口的所有IP地址
            QList<QNetworkAddressEntry> entries = interface.addressEntries();

            // 遍历每个IP地址
            for (const QNetworkAddressEntry &entry : entries) {
                // 排除非IPv4地址
                if (entry.ip().protocol() == QAbstractSocket::IPv4Protocol) {
                    // 输出WiFi的IPv4地址信息
                    qDebug() << "WiFi Interface:" << interface.name();
                    qDebug() << "WiFi IPv4 Address:" << entry.ip().toString();
                    qDebug() << "WiFi Netmask:" << entry.netmask().toString();
                    qDebug() << "WiFi Broadcast:" << entry.broadcast().toString();
                    qDebug() << "-----------------------------------";
                    address=entry.ip().toString().toStdString();
                }
            }
        }
    }
    return address;
}


void client::on_pushButton_clicked()
{
    std::string ip=ipTxt->text().toStdString();
    std::string port=portTxt->text().toStdString();
    qDebug()<<ip;
    qDebug()<<port;
     myTcpClient=new MyTcpClient(instance,ip,stoi(port));
    myTcpClient->connectServer();
}


void client::on_btnSend_clicked()
{
    qDebug()<<(myTcpClient!=nullptr);
    if (myTcpClient!=nullptr) {
        QString msg=sendMsgEdit->toPlainText();
        myTcpClient->sendMsgToServer(msg.toStdString());
    }else{
        QMessageBox::information(nullptr,QString::fromStdString("alert"),QString::fromStdString("客户端未连接"));
    }

}


void client::on_btnClear_clicked()
{

}

